/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState } from 'react';
import type { ConnectState } from '@/models/connect';
import { connect } from 'umi';
import {
  Form,
  Input,
  Button,
  DatePicker,
  Typography,
  Row,
  Col,
  Card,
  message,
  Select,
  Spin,
  Space,
} from 'antd';
import CommonColumns from './_common/CommonColumns';
import type { AccountInfo } from '../types/InnAccountInfo';
import type { Moment } from 'moment';
import { getRanString } from './utils';
import { getMobileData, getBrandList } from '@/services/customerSearch';
import CommonTable from './_common/CommonTable';
import moment from 'moment';
import { isArray } from 'lodash';
const FormItem = Form.Item;
const { Title } = Typography;

interface InnAccountInfoType {
  screenSize?: boolean;
  dispatch: any;
  accountInfo: AccountInfo;
  tableLoading: boolean;
}
interface FormValuesType {
  psw?: string;
  time?: Moment;
  brand?: string | undefined;
  waybillno?: string | undefined;
}

const { Option } = Select;
const InnAccountInfo = (props: InnAccountInfoType) => {
  const [datasource, setDatasource] = useState<{ head: any[]; list: any[] }[]>([]);
  const [queryOrder, setQueryOrder] = useState<any[]>([]);
  const [searchSource, setSearchSource] = useState({});
  const [brandList, setBrandList] = useState<{ label: string; value: string }[]>([]);
  const { screenSize, tableLoading } = props;
  const [columns, setColumns] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();

  const onFinish = async (values: FormValuesType) => {
    setLoading(true);
    const { time, waybillno, brand = '' } = values;
    const { code, data, msg } = await getMobileData({
      brand,
      waybillno,
      date: moment(time).format('YYYY-MM-DD'),
    });
    setLoading(false);
    if (code == 0) {
      const {
        logData: { queryLog = [], setting = {}, res: { title = '', phone: mobile = '' } = {} } = {},
        supplierQuery,
      } = data;
      // const { title, phone: mobile } = queryLog.slice(-1)[0] || {};
      setting['channel'] = title;
      setting['result'] = mobile;
      const data_source: any = {};
      const columnsList: any = Object.keys(supplierQuery).map((item) => {
        const { phone, privacy } = supplierQuery[item];
        data_source[item] = {
          desc: privacy ? '隐私面单' : '',
          key: phone || '不可发',
        };
        return {
          title: supplierQuery[item].name,
          dataIndex: item,
          align: 'center',
          search: false,
          width: 130,
          render: (_: any, record: any) => {
            const { desc, key } = record[item];
            return (
              <Space direction='vertical'>
                <div>{key}</div>
                <div>{desc}</div>
              </Space>
            );
          },
        };
      });
      setSearchSource(setting);
      setColumns(columnsList);
      setQueryOrder(queryLog);
      setDatasource([data_source]);
    } else {
      message.error(msg);
      setSearchSource({});
      setColumns([]);
      setQueryOrder([]);
      setDatasource([]);
    }
  };

  useEffect(() => {
    getBrandList().then((res) => {
      const { data } = res;
      setBrandList(data);
    });
  }, []);

  return (
    <>
      <Form
        form={form}
        onFinish={onFinish}
        layout={screenSize ? 'vertical' : 'inline'}
        initialValues={{
          time: moment(),
        }}
        style={{ marginBottom: 20 }}
      >
        <FormItem
          label={'运单号'}
          name='waybillno'
          rules={[{ required: true, message: '请输入运单号' }]}
        >
          <Input allowClear style={{ width: 250 }} placeholder={'请输入运单号（必填）'} />
        </FormItem>
        <FormItem label={'品牌'} name='brand' rules={[{ required: true, message: '请选择品牌' }]}>
          <Select style={{ width: 200 }}>
            {brandList.map((item) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </FormItem>
        <FormItem label={'日期'} name='time'>
          <DatePicker style={{ width: 200 }} disabledDate={(event) => event > moment()} />
        </FormItem>

        <FormItem>
          <Button type='primary' htmlType='submit' loading={false}>
            查询
          </Button>
        </FormItem>
      </Form>

      <Spin spinning={loading}>
        <CommonTable
          title='渠道查询'
          columns={columns}
          datasource={datasource}
          loading={tableLoading}
        />
        <Title level={5} style={{ padding: 16 }}>
          查询结果
        </Title>
        <Row gutter={[20, 20]}>
          <Col span={10}>
            <div style={{ background: '#fafafa', padding: 20, textAlign: 'center' }}>查询顺序</div>
            <Card key={getRanString()} style={{ marginBottom: 20 }}>
              {queryOrder.map((item) => (
                <Row key={getRanString()} style={{ marginTop: 5 }}>
                  <Col span={11} offset={1} style={{ textAlign: 'right' }}>
                    {item.title}:
                  </Col>
                  <Col span={11} offset={1}>
                    {item.phone}{' '}
                  </Col>
                  {isArray(item?.res?.sn) && (
                    <Col offset={13}>{'【' + item?.res?.sn.join('、') + '】'}</Col>
                  )}
                </Row>
              ))}
            </Card>
          </Col>
          <Col span={10}>
            <div style={{ background: '#fafafa', padding: 20, textAlign: 'center' }}>
              最终查询结果
            </div>
            <CommonColumns
              screenSize
              data={searchSource}
              columns={[
                {
                  title: '查询渠道',
                  dataIndex: 'channel',
                },
                {
                  title: '查询结果',
                  dataIndex: 'result',
                },
                {
                  title: '中通代收是否开启',
                  dataIndex: 'zt',
                  render: () => (searchSource['zt'] ? '是' : '否'),
                },
                {
                  title: '顺丰代收是否开启',
                  dataIndex: 'sf_star',
                  render: () => (searchSource['sf_star'] ? '是' : '否'),
                },
                {
                  title: '自动带出手机号是否开启',
                  dataIndex: 'is_open',
                  render: () => (searchSource['is_open'] ? '是' : '否'),
                },
              ]}
            />
          </Col>
        </Row>
      </Spin>
    </>
  );
};

export default connect(({ customerSearch, loading }: ConnectState) => ({
  accountInfo: customerSearch.innAccountInfoData?.account_info || {},
  innAccountInfoData: customerSearch.innAccountInfoData,
  tableLoading: loading.effects['customerSearch/innAccountInfo'] || false,
}))(React.memo(InnAccountInfo));
